package org.opens.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.opens.dao.OrderDao;
import org.opens.entity.Order;
import org.opens.service.OrderService;
import org.opens.service.fallback.OrderServiceFallback;
import org.opens.service.handle.OrderServiceBlockHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    private int i = 0;

    @Override
    public Order save(Order order) {
        Assert.notNull(order, "保存订单不能为空");
        Order saveOrder = orderDao.save(order);
        return saveOrder;
    }

    // 定义Sentinel资源, 指定资源名称
    @SentinelResource(
            value = "message",
            fallbackClass = OrderServiceFallback.class,
            fallback = "message",
            blockHandlerClass = OrderServiceBlockHandle.class,
            blockHandler = "message"
    )
    @Override
    public String message(String message) {
        i += 1;
        if (i % 3 == 0) {
            throw new RuntimeException("每三次触发一次");
        }
        return message;
    }
}
